//
//  BubbleItemView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/7/24.
//

import SwiftUI

struct BubbleItemView: View {
    @State var bean: BubbleMallBean
    let itemWidth: CGFloat
    let isSelected: Bool
    @StateObject var viewModel = BubbleViewModel()
    @StateObject private var paymentManager = PaymentManager()
    @State private var showBuyDialog = false //删除

    var body: some View {
        VStack {
            ZStack {
                BubbleChatView(str: "哈喽", bean: BubbleExt.getBubble(id: bean.id) ?? BubbleBean())
            }.frame(width: itemWidth,height: itemWidth)
                .background(.bgItem)
                .clipShape(RoundedRectangle(cornerRadius: 8))
            ZStack{
                Text("¥\(formatPrice(bean.price ?? 0))")
                    .foregroundStyle(.bgNormalText)
                    .font(.system(size: 14))
                    .frame(maxWidth: .infinity, alignment: .leading)
                Button(action: {
                    if !userManager.isLogin() {
                        showLoginPopup()
                        return
                    }
                    viewModel.checkExit(id: bean.id ?? "") {
                        let myBubbleCount =  userManager.getExtraConfig().bubbleCount ?? 0
                        let bubbleCount = bean.bubbleCount ?? 1
                        if (myBubbleCount > 0) {
                            if (myBubbleCount >= bubbleCount) {
                                showBtnDialog(text: "是否解锁该气泡？需消耗 \(bubbleCount) 次进行解锁", btn: "解锁") {
                                    viewModel.doCreate(bean: bean, deduct: true)
                                }
                            } else {
                                showBtnDialog(text: "是否解锁该气泡？需消耗 \(bubbleCount) 次进行解锁，您当前次数不足，可通过在线支付完成解锁～", btn: "解锁") {
                                    showBuyDialog = true
                                }
                            }

                        } else {
                            showBuyDialog = true
                        }
                    }
                }) {
                    Text("购买")
                        .foregroundColor(themeManager.themeColor)
                        .font(.system(size: 12))
                        .padding(.horizontal,20)
                        .padding(.vertical,5)
                    
                }.background(themeManager.themeColor.opacity(0.1))
                    .cornerRadius(5)
                    .frame(maxWidth: .infinity, alignment: .center)
            }
        }.frame(width: itemWidth)
            .alert("温馨提示",isPresented:$showBuyDialog) {
                Button("取消",role: .cancel){}
                Button("确定购买",role: .destructive) {
                    viewModel.getPay(bean: bean)
                    showLoadPopup()
                    //执行购买
                    paymentManager.purchaseProduct(withIdentifier: bean.productId ?? "") { result in
                        // 处理回调结果
                        switch result {
                        case .purchasing:
                            showLog("正在购买...")
                        case .purchased:
                            showLog("购买成功")
                            viewModel.doCreate(bean: bean, deduct: false)
                        case .failed(let errorMessage):
                            hideLoadPopup()
                            showLog("购买失败: \(errorMessage)")
                        case .restored(let productID):
                            showLog("恢复购买成功，产品 ID: \(productID)")
                            viewModel.doCreate(bean: bean, deduct: false)
                        case .deferred:
                            showLog("购买延迟处理")
                        case .invalidProductID:
                            hideLoadPopup()
                            showLog("未找到有效的产品 ID")
                            showToast("未找到有效的产品 ID")
                        case .unknown:
                            showLog("未知交易状态")
                        }
                    }
                }
            }
    }
}

private let previewBean: BubbleMallBean = {
    let bean : BubbleMallBean = BubbleMallBean()
    bean.id = "30"
    return bean
}()

#Preview {
    BubbleItemView(bean: previewBean, itemWidth: 300, isSelected: true)
}
